<template>
  <div class="myKnowledge">
    <div v-if="currentPageName == 'tool'" class="filePage">
      <crumb :list="crumbList" @goBack="goBack" @gotoPage="gotoPage" :right="true"></crumb>
      <!-- <div class="goBack" @click="goBack"><i class="el-icon-back"></i>返回上一级</div> -->
      <conditionalQuery @search="search"></conditionalQuery>
      <div class="fileTable">
        <div class="fristRow">
          <div class="title">工具列表</div>
          <div class="btnGroup">
            <el-button v-if="userRole" size="medium" @click="handleDialog('文件上传')"> <i class="iconfont icon-shangchuan" />文件上传 </el-button>
            <!-- <el-button v-if="userRole" size="medium" @click="templateUpload"> <i class="iconfont icon-yunduanxiazai" />模板下载 </el-button> -->
          </div>
        </div>
        <div style="height: calc(100% - 100px)">
          <el-table ref="multipleTable" :data="tableData" tooltip-effect="dark" height="100%" class="costomTable" v-loading="loading">
            <el-table-column type="selection" width="55" align="center"> </el-table-column>
            <el-table-column type="index" label="序号"> </el-table-column>
            <el-table-column prop="resourceName" width="350" label="文件名" show-overflow-tooltip />
            <el-table-column prop="description" label="简介" show-overflow-tooltip />
            <el-table-column align="center" prop="statusCode" label="连接状态" show-overflow-tooltip>
              <template slot-scope="scope">
                <img v-if="scope.row.statusCode == 200" src="@/assets/image/icon/zc.svg" alt="" />
                <img v-else src="@/assets/image/icon/yc.svg" width="16" height="16" alt="" />
              </template>
            </el-table-column>
            <el-table-column prop="realName" label="创建人" show-overflow-tooltip />
            <el-table-column prop="gmtCreated" label="创建时间" show-overflow-tooltip>
              <template slot-scope="scope">
                {{ $dayjs(scope.row.gmtCreated).format("YYYY-MM-DD HH:mm:ss") }}
              </template>
            </el-table-column>
            <el-table-column v-if="userRole" label="操作" show-overflow-tooltip width="350">
              <template slot-scope="scope">
                <div class="operateGroup">
                  <div @click="handlePrompt(scope.row)"><i class="iconfont icon-bianji" />prompt</div>
                  <div @click="handelShots(scope.row)"><i class="iconfont icon-bianji" />shots</div>
                  <div @click="handelTestLink(scope.row)"><i class="iconfont icon-bianji" />测试连接</div>
                  <div @click="deleteFile(scope.row)"><i class="el-icon-delete" style="margin-right: 5px" />删除</div>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <pageInation :total="total" @handleCurrentChange="handleCurrentChange"> </pageInation>
      </div>
      <!-- </div> -->
    </div>
    <!-- 工具集 -->
    <toolsSetof @changeTools="changeTools" v-else-if="currentPageName == 'toolsSetof'"></toolsSetof>
    <!-- 文件上传 -->
    <parentDialog :title="dialogTitle" :visible.sync="dialogVisible" v-if="dialogVisible" :height="dialogHeight">
      <el-upload
        v-if="dialogVisible && dialogTitle == '文件上传'"
        v-loading="loading"
        class="upload-demo"
        drag
        :on-remove="handleRemove"
        :on-change="handleChange"
        :file-list="fileList"
        multiple
        :limit="2"
        :on-exceed="handleExceed"
        :auto-upload="false"
        action="">
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="upload_tip_tool" @click="templateUpload" slot="tip">只能上传json文件（<span>点击下载模板</span>）</div>
      </el-upload>
      <shot
        v-else-if="dialogVisible && dialogTitle.includes('shot')"
        :tkName="toolsSetofInfo.tkName"
        :toolName="toolInfo.resourceName"
        :toolInfo="toolInfo"></shot>
      <prompt
        v-else-if="dialogVisible && dialogTitle.includes('Prompt')"
        @closeDialog="dialogVisible = false"
        :tkName="toolsSetofInfo.tkName"
        :toolName="toolInfo.resourceName"
        :toolId="toolInfo.id"
        :toolInfo="toolInfo"></prompt>
      <div class="btn" v-if="dialogVisible && dialogTitle == '文件上传'">
        <el-button size="medium" type="primary" @click="upLoad">上传</el-button>
        <el-button size="medium" @click="dialogVisible = false">取消</el-button>
      </div>
    </parentDialog>
  </div>
</template>

<script>
import parentDialog from "@/components/dialog/parentDialog.vue" // 弹窗
import pageInation from "@/components/pageInation/index.vue"
import { registryList, registryDelete, registryAdd, registryCheck } from "@/api/tools"
import conditionalQuery from "@/components/conditionalQuery/index.vue" // 查询参数
import toolsSetof from "./toolsSetof.vue"
import crumb from "@/components/pageInation/crumb.vue"
import { mixins } from "@/components/mixin/tools"
import { downLoad, delay } from "@/utils/index"

export default {
  components: {
    conditionalQuery,
    pageInation,
    parentDialog,
    toolsSetof,
    crumb,
  },
  mixins: [mixins],
  data() {
    return {
      tableData: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      dialogVisible: false,
      dialogTitle: "",
      fileList: [],
      params: {},
      tagInput: "",
      loading: false,
      currentPageName: "toolsSetof",
      toolsSetofInfo: {}, // 工具集信息
      toolInfo: {},
    }
  },

  computed: {
    userRole() {
      return localStorage.getItem("roles") == "超级管理员"
    },
    crumbList() {
      return ["知识库服务 ", "公共工具集", this.toolsSetofInfo.tkName]
    },
  },
  mounted() {},
  methods: {
    getTableList() {
      this.loading = true
      registryList({
        page: this.currentPage,
        size: this.pageSize,
        // name: this.params.fileName || "",
        tools: this.toolsSetofInfo.tkName,
      })
        .then(result => {
          console.log(result)
          this.tableData = result.data.records
          this.total = result.data?.total
          this.loading = false
        })
        .catch(err => {
          this.loading = false
        })
    },
    // 模板下载
    templateUpload() {
      let url = "/static/file/toolJsonTemplate.json"
      downLoad("toolJsonTemplate.json", url)
    },
    // 分页事件
    handleCurrentChange(item) {
      this.currentPage = item.currentPage
      this.pageSize = item.pageSize
      this.getTableList()
    },
    // 删除
    deleteFile(row) {
      let fileNameList = [],
        fileIdList = []
      if (row["id"]) {
        fileNameList = [row.fileName]
        fileIdList = [row.id]
      } else {
        let selection = this.$refs.multipleTable.selection
        if (selection.length) {
          fileNameList = selection.map(v => v.fileName)
          fileIdList = selection.map(v => v.id)
        }
      }

      if (!fileIdList.length) {
        this.$message.warning("请先选择文件")
        return
      }
      this.$confirm("确定删除文件?", "提示", {
        cancelButtonText: "取消",
        confirmButtonText: "确定",
        type: "warning",
      }).then(() => {
        registryDelete({
          id: row.id,
        })
          .then(result => {
            console.log(result, "resultresultresultresult")
            if (result.code == "200") {
              this.$message.success(result.msg)
              this.getTableList()
            }
          })
          .catch(err => {
            this.$message.warning(err)
          })
      })
    },
    // 链接测试
    handelTestLink(row) {
      registryCheck({
        id: row.id,
      })
        .then(result => {
          console.log(result)
          row.statusCode = result.data.status_code
          if (result.data.status_code == 200) this.$message.success("连接成功")
          else this.$message.error("连接失败")
        })
        .catch(err => {
          console.log(err)
        })
    },
    handleRemove(file, fileList) {
      this.fileList = fileList
      console.log(file, fileList)
    },
    handleChange(file, fileList) {
      this.fileList = fileList
    },
    handleExceed(file, fileList) {
      this.$message.warning(`仅支持单文件上传`)
    },

    upLoad() {
      console.log(this.fileList)
      if (!this.fileList.length) {
        this.$message.warning("请先选择文件")
        return
      }
      let fileTypeArr = ["json", "yaml"]
      let formatData = new FormData()
      let bool = false
      this.fileList.forEach(item => {
        if (fileTypeArr.includes(item.name.split(".").at(-1))) {
          formatData.append("file", item.raw)
        } else {
          bool = true
        }
      })
      if (bool) {
        this.$message.warning("仅支持上传json类型文件")
        return
      }
      formatData.append("tools", this.toolsSetofInfo.tkName)
      registryAdd(formatData)
        .then(result => {
          console.log(result)
          if (result.code == 200) {
            this.$message.success(result.msg)
            this.getTableList()
            this.dialogVisible = false
            this.fileList = []
          } else {
            this.$message.warning(result.msg)
          }
        })
        .catch(err => {
          console.log(err)
        })
    },

    goBack() {
      if (this.currentPageName == "tool") {
        this.currentPageName = "toolsSetof"
      } else if (this.currentPageName == "filedDetails") {
        this.currentPageName = "filePage"
      }
    },
    gotoPage(item) {
      if (item == "公共工具集") {
        this.currentPageName = "toolsSetof"
      }
    },

    // 查询事件
    search(obj) {
      let { fileName, screening, fileState } = obj
      this.currentPage = 1
      this.params.fileName = fileName
      this.params.screening = screening
      this.params.fileState = fileState
      this.getTableList()
    },
    changeTools(row) {
      this.currentPageName = "tool"
      this.toolsSetofInfo = row
      this.fileList = []
      this.getTableList()
    },
    handleDialog(title) {
      this.fileList = []
      this.dialogHeight = "45%"
      this.dialogTitle = title
      this.dialogVisible = true
    },
  },
}
</script>
<style lang="scss" scoped>
.myKnowledge {
  width: 100%;
  height: calc(100%);
  background: #e6eaf0;
  position: relative;
  .filePage {
    width: 100%;
    height: calc(100%);
    .goBack {
      margin-bottom: 10px;
      margin-left: 5px;
      margin-right: 5px;
      text-align: right;
      cursor: pointer;
    }
    .fileTable {
      background: #fff;
      margin-top: 20px;
      padding: 20px;
      border-radius: 8px;
      height: calc(100% - 142px);
      box-sizing: border-box;
      .filerName {
        display: flex;
        align-items: center;
        > img {
          margin-right: 5px;
        }
      }
      .fristRow {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding-bottom: 10px;
        margin-bottom: 20px;
        border-bottom: 1px solid rgba(0, 20, 45, 0.05);
        .title {
          font-family: MiSans, MiSans;
          font-weight: 600;
          color: #00142d;
          line-height: 24px;
        }
      }
      .analysisProgress {
        // margin-right: 15px;
        &:nth-child(1) {
          display: flex;
          justify-content: space-between;
        }
        :nth-child(2) {
          color: rgba(0, 20, 45, 0.5);
        }
      }
      .operateGroup {
        display: flex;
        .iconfont {
          margin-right: 3px;
        }
        > div {
          margin-right: 15px;
          cursor: pointer;
          &:hover {
            color: #409eff;
          }
        }
      }
    }
  }
  .uploadBox {
    height: calc(100% - 60px);
  }
  .templateUpload {
    text-align: right;
  }
  .btn {
    margin-top: 15px;
  }
  ::v-deep .el-upload-list__item {
    text-align: left;
    padding-left: 180px;
  }
  .upload_tip_tool {
    font-size: 14px;
    text-align: left;
    padding-left: 190px;
    margin-top: 10px;
    > span {
      color: #409eff;
      cursor: pointer;
      :hover {
        transform: scale(1.1);
      }
    }
  }
}
</style>
